package dao.hibernate;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.MultiMap;
import org.apache.commons.collections.iterators.EntrySetMapIterator;

import util.Util;

import model.LoaiThuoc;
import dao.LoaiThuocDAO;

public class LoaiThuocDAOHibernate extends GenericHibernateDAO<LoaiThuoc, Long>
		implements LoaiThuocDAO {

	@SuppressWarnings("unchecked")
	@Override
	public List<LoaiThuoc> findByIDLoaiThuoc(String name) {
		return getSession()
				.createQuery(
						"FROM LoaiThuoc AS loaiThuoc WHERE loaiThuoc.idLoaiThuoc LIKE :pname")
				.setString("pname", "%" + name + "%").list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<LoaiThuoc> findByTenLoaiThuoc(String name) {
		return getSession()
				.createQuery(
						"FROM LoaiThuoc AS loaiThuoc WHERE loaiThuoc.tenLoaiThuoc LIKE :pname")
				.setString("pname", "%" + name + "%").list();
	}

	public List<LoaiThuoc> findByOneCondition(String criteria, String keyWord) {
		List<LoaiThuoc> result = new ArrayList<LoaiThuoc>();
		if (criteria.equals("tenChuDe")) {
			result = findByTenLoaiThuoc(keyWord);
		} else if (criteria.equals("idLoaiThuoc")) {
			result = findByIDLoaiThuoc(keyWord);
		}
		return result;
	}

	@Override
	public List<LoaiThuoc> findByKeyword(String keyword) {
		// TODO Auto-generated method stub
		return null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<LoaiThuoc> findByManyConditions(MultiMap conditions) {
		List<LoaiThuoc> result = null;
		EntrySetMapIterator iterator = new EntrySetMapIterator(conditions);
		String criteria = "";
		List<String> keywords = new ArrayList<String>();
		String keyword = "";
		while (iterator.hasNext()) {
			criteria = (String) iterator.next();
			keywords = (ArrayList<String>) conditions.get(criteria);
			for (String k : keywords) {
				keyword = k;
				if (criteria.equals("tenLoaiThuoc")) {
					List<LoaiThuoc> list = findByTenLoaiThuoc(keyword);
					result = Util.retainAllLoaiThuoc(result, list);
				}
			}
		}
		return result;
	}
}
